// 问卷调查
import React, { useState, useReducer } from "react";
import { store } from "../../store/index";
import queryApi, { fileWeb } from "../../api/query";
import { Alert } from "react-native";
import { condition } from "../../data/condition";

import * as XLSX from "xlsx";
import * as FileSystem from "expo-file-system";
import * as Sharing from "expo-sharing";

const MyQuesContext = React.createContext();

const typeOptions = [
  "脱贫稳定户",
  "脱贫不稳定户",
  "突发困难严重户1",
  "突发困难严重户2",
  "边缘易致贫户",
  "其他户",
  "全部",
];

const dataReducer = (state, action) => {
  switch (action.type) {
    case "add_data":
      // console.log("为啥不成功---", action.payload.newQues);
      return [action.payload.newQues, ...state];
    case "edit_myques":
      return state.map((preQues, quesIndex) => {
        return quesIndex == action.payload.index
          ? {
              ...action.payload.req_data,
              opinions: preQues.opinions,
              userproblem: preQues.userproblem,
              filedata: preQues.filedata,
              user: preQues.user,
              target: action.payload.req_data.body[0].contents[5].answer,
            }
          : preQues;
      });
    // 编辑问题清单
    case "edit_problem":
      return state.map((ques, index) => {
        return index == action.payload.quesIndex
          ? {
              ...ques,
              userproblem: action.payload.userproblem,
            }
          : ques;
      });
    case "get_ques":
      return [...action.payload.myquesArr];
    // 编辑问卷状态
    case "edit_state":
      return state.map((ques, index) => {
        return index == action.payload.index
          ? {
              ...ques,
              state: action.payload.t_state,
            }
          : ques;
      });
    // 回复
    case "edit_opinions":
      return state.map((ques, index) => {
        return index == action.payload.quesIndex
          ? {
              ...ques,
              opinions: action.payload.opinions,
            }
          : ques;
      });
    // 入户资料
    case "edit_filedata":
      return state.map((ques, index) => {
        return index == action.payload.quesIndex
          ? {
              ...ques,
              filedata: action.payload.filedata,
            }
          : ques;
      });
    case "delete_myques":
      return state.filter((item, index) => index != action.payload.quesIndex);

    default:
      return state;
  }
};

// let newQuesData = {
//   target: -1, // 0：一般户
//   title: "SD-054-060202-BY001",
//   state: 3,
//   group: "",
//   time: "",
//   user: {},
//   filedata: "",
//   userproblem: "",
//   body: [],
// };

let initData = [];

export const MyQuesProvider = ({ children }) => {
  const [MyQuesData, dispatch] = useReducer(dataReducer, initData);
  const [myQuesLoading, setMyQuesLoading] = useState("end");
  const [fileDataLoading, setFileDataLoading] = useState("end");
  const [userProLoading, setUserProLoading] = useState("end");
  const [villageArr, setVillageArr] = useState(["全部"]);
  const [errorAlter, setErrorAlter] = useState("");
  const [conditionAlter, setConditionAlter] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [pageLen, setPageLen] = useState(0);

  // 添加新闻卷
  const addNewQues = async (newQues, callback) => {
    try {
      await postMyOneQues(newQues, 0, callback);
    } catch (error) {
      callback(false);
      Alert.alert("保存失败");
      console.log("新问卷保存失败---", error);
    }
  };

  // 暂存问卷
  const editMyQues = async (quesIndex, Ques, callback) => {
    try {
      let req_data = {
        ...Ques,
        opinions: Ques.opinions._id,
        userproblem: Ques.userproblem._id,
        filedata: Ques.filedata._id,
        target: Ques.body[0].contents[5].answer,
        user: Ques.user._id,
        time: new Date(),
      };
      let data = await queryApi.patch("userques/", {
        Ques: req_data,
        flag: "edit",
      });
      console.log("暂存问卷成功---", data.data.status);
      dispatch({
        type: "edit_myques",
        payload: { index: quesIndex, req_data },
      });
      callback(true);
      Alert.alert("暂存成功");
    } catch (error) {
      callback(false);
      Alert.alert("暂存失败");
      console.log("暂存问卷失败---", error);
    }
  };

  // 保存
  const editAndJudgeMyQues = async (quesIndex, callback) => {
    setErrorAlter("");
    setConditionAlter("");
    let errorStr = "";
    if (MyQuesData[quesIndex].title == "") {
      errorStr = errorStr + "问卷编号,";
    }
    for (let i = 0; i < MyQuesData[quesIndex].body.length; i++) {
      if (MyQuesData[quesIndex].body[i].visible) {
        for (
          let j = 0;
          j < MyQuesData[quesIndex].body[i].contents.length;
          j++
        ) {
          let t_contents = MyQuesData[quesIndex].body[i].contents[j];
          if (t_contents.visible) {
            if (
              (t_contents.type == 1 || t_contents.type == 7) &&
              t_contents.answer == ""
            ) {
              errorStr =
                errorStr + String.fromCharCode(i + 65) + (j + 1) + "，";
            } else if (
              t_contents.type == 2 &&
              (t_contents.answer < 0 ||
                t_contents.answer >= t_contents.options.length)
            ) {
              errorStr =
                errorStr + String.fromCharCode(i + 65) + (j + 1) + "，";
            } else if (t_contents.type == 3) {
              let flag = t_contents.answer[0];
              for (let n = 1; n < t_contents.answer.length; n++) {
                flag = flag || t_contents.answer[n];
              }
              if (!flag)
                errorStr =
                  errorStr + String.fromCharCode(i + 65) + (j + 1) + "，";
            } else if (t_contents.type == 5) {
              for (let k = 0; k < t_contents.title.length; k++) {
                let t_title = t_contents.title[k];
                if (t_title.visible) {
                  if (
                    (t_title.type == 1 || t_title.type == 7) &&
                    t_title.answer == ""
                  ) {
                    errorStr =
                      errorStr +
                      String.fromCharCode(i + 65) +
                      (j + 1) +
                      String.fromCharCode(k + 97) +
                      "，";
                  } else if (
                    t_title.type == 2 &&
                    (t_title.answer < 0 ||
                      t_title.answer >= t_title.options.length)
                  ) {
                    errorStr =
                      errorStr +
                      String.fromCharCode(i + 65) +
                      (j + 1) +
                      String.fromCharCode(k + 97) +
                      "，";
                  } else if (t_title.type == 3) {
                    let flag = t_title.answer[0];
                    for (let n = 1; n < t_title.answer.length; n++) {
                      flag = flag || t_title.answer[n];
                    }
                    if (!flag)
                      errorStr =
                        errorStr +
                        String.fromCharCode(i + 65) +
                        (j + 1) +
                        String.fromCharCode(k + 97) +
                        "，";
                  } else if (t_title.type == 6) {
                    console.log("位置---", t_title.answer);
                    if (
                      t_title.answer[0] == "" ||
                      t_title.answer < 1 ||
                      t_title.answer[0] == null
                    ) {
                      errorStr = errorStr + "A1a，";
                    }
                    if (
                      t_title.answer[1] == "" ||
                      t_title.answer < 2 ||
                      t_title.answer[1] == null
                    ) {
                      errorStr = errorStr + "A1b，";
                    }
                    if (
                      t_title.answer[2] == "" ||
                      t_title.answer < 3 ||
                      t_title.answer[2] == null
                    ) {
                      errorStr = errorStr + "A1c，";
                    }
                    if (
                      t_title.answer[3] == "" ||
                      t_title.answer < 4 ||
                      t_title.answer[3] == null
                    ) {
                      errorStr = errorStr + "A1d，";
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    setErrorAlter(errorStr);
    console.log("没填的---", errorStr);
    if (errorStr == "") {
      console.log("开始条件判断");
      let c2Flag = false;
      let conditionStr = "";
      for (let a = 0; a < condition.length; a++) {
        let goonFlag = true;
        if (condition[a].num.length == 2) {
          goonFlag =
            MyQuesData[quesIndex].body[condition[a].num[0]].contents[
              condition[a].num[1]
            ].visible &&
            MyQuesData[quesIndex].body[condition[a].num[0]].visible;
        } else {
          console.log(condition[a].num);
          goonFlag =
            MyQuesData[quesIndex].body[condition[a].num[0]].contents[
              condition[a].num[1]
            ].title[condition[a].num[2]].visible &&
            MyQuesData[quesIndex].body[condition[a].num[0]].contents[
              condition[a].num[1]
            ].visible &&
            MyQuesData[quesIndex].body[condition[a].num[0]].visible;
        }
        if (goonFlag) {
          let left = 0;
          let right = 0;
          let t_num = [];
          left = getNumAnswer(quesIndex, condition[a].num);

          for (let b = 0; b < condition[a].conType.length; b++) {
            right = 0;
            if (condition[a].conType[b] == 0) {
              // 是否等于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                // console.log("---", right);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
                // console.log("++", right);
              }
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left != right) {
                console.log(
                  "右---",
                  right,
                  "---有错---",
                  condition[a].conStr[b]
                );
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 1) {
              // 大于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              // console.log(">1 右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left <= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 2) {
              // 大于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log(">2 右---", right);
              if (left <= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 3) {
              // 小于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              // console.log("<1 右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left >= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 4) {
              // 小于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log("<2 右---", right);
              if (left >= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 5) {
              // 大于等于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              // console.log(">=1 右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left < right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 6) {
              // 大于等于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log(">=2 右---", right);
              if (left < right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 7) {
              // 小于等于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                console.log("a---", a);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              console.log("<=1 ", "左--", left, "右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left > right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 8) {
              // 小于等于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log("<=2 右---", right);
              if (left > right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            }
          }
        }
      }
      setConditionAlter(conditionStr);
      console.log("填错的---", conditionAlter);
      if (conditionStr == "") {
        try {
          let ques_data = {
            ...MyQuesData[quesIndex],
            opinions: MyQuesData[quesIndex].opinions._id,
            userproblem: MyQuesData[quesIndex].userproblem._id,
            filedata: MyQuesData[quesIndex].filedata._id,
            target: MyQuesData[quesIndex].body[0].contents[5].answer,
            user: MyQuesData[quesIndex].user._id,
            group: MyQuesData[quesIndex].user.group,

            time: new Date(),
          };
          // console.log("上传---", ques_data.filedata);
          let ques_req_data = await queryApi.patch("userques/", {
            Ques: ques_data,
            flag: "edit",
          });
          console.log("保存用户问卷成功---", ques_req_data.data.status);
          // dispatch({
          //   type: "edit_myques",
          //   payload: { index: quesIndex, req_data: ques_data },
          // });
          Alert.alert("保存问卷成功");
          callback(true);
        } catch (error) {
          callback(false);
          console.log("保存问卷失败---", error);
          Alert.alert("保存问卷失败");
        }
      }
    }
  };

  // 修改问题清单
  const editQuesProblem = async (
    quesIndex,
    editData,
    originImages,
    deleteOriginImages,
    originAudio,
    deleteOriginAudio,
    originVideos,
    deleteOriginVideos,
    callback
  ) => {
    setUserProLoading("ing");
    console.log("问题清单---", editData);
    try {
      if (
        editData.image.length != 0 ||
        editData.video.length != 0 ||
        editData.soundfile.length != 0 ||
        deleteOriginImages.length != 0 ||
        deleteOriginVideos.length != 0 ||
        deleteOriginAudio.length != 0 ||
        originImages.length != 0 ||
        originAudio.length != 0
      ) {
        let formData = new FormData();
        if (editData.image.length != 0) {
          editData.image.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "image/" + item.split(".").pop(),
            });
          });
        }
        if (editData.video.length != 0) {
          editData.video.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "video/" + item.split(".").pop(),
            });
          });
        }
        if (editData.soundfile.length != 0) {
          editData.soundfile.forEach((item) => {
            formData.append("files", {
              name: item.uri.split("/").pop(),
              uri: item.uri,
              type: "audio/" + item.uri.split(".").pop(),
            });
          });
        }
        //需删除的原始图片、视频
        if (deleteOriginImages.length != 0) {
          deleteOriginImages.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        if (deleteOriginVideos.length != 0) {
          deleteOriginVideos.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        if (deleteOriginAudio.length != 0) {
          deleteOriginAudio.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        //需保留的原始图片、视频
        if (originImages.length != 0) {
          originImages.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        if (originVideos.length != 0) {
          originVideos.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        if (originAudio.length != 0) {
          originAudio.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        console.log(
          "----------userproblem file request-------------",
          formData
        );
        let res = await fetch(fileWeb + "/upload/multi", {
          method: "patch",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          body: formData,
        });
        let response = await res.json();
        console.log("w这");
        editData.image = response.message.filter(
          (item) => item.fileType.split("/").shift() == "image"
        );
        editData.video = response.message.filter(
          (item) => item.fileType.split("/").shift() == "video"
        );
        editData.soundfile = response.message.filter(
          (item) => item.fileType.split("/").shift() == "audio"
        );
        // console.log("问题清单开始往后端传啦", editData);
      }
      //对后端进行修改
      const result = await queryApi.patch(
        "/userproblem/" + editData._id,
        editData
      );
      console.log("修改问题清单成功---", result.data.status);
      let AllData = await queryApi.get("userproblem/" + editData._id);
      console.log("获取新的问题清单成功---", AllData.data.status);
      dispatch({
        type: "edit_problem",
        payload: { quesIndex: quesIndex, userproblem: AllData.data.data },
      });
      setUserProLoading("end");
      callback(true);
      Alert.alert("更新问题清单成功");
    } catch (error) {
      Alert.alert("更新问题清单失败");
      callback(false);
      setUserProLoading("error");
      console.log("修改问题清单失败---", error);
    }
  };

  const getMyQues = async (pageIndex) => {
    try {
      setMyQuesLoading("ing");
      const user = store.getState().authR.user;
      // console.log("user---", user);
      let data = await queryApi.get(
        "userques/byuserpage/" +
          user._id +
          "?page=" +
          pageIndex +
          "&pageSize=" +
          pageSize
      );
      console.log("查找我的问卷成功---", data.data.status);
      // console.log(data.data.data[1].userproblem);
      let myquesArr = data.data.data;
      dispatch({ type: "get_ques", payload: { myquesArr: myquesArr } });
      setPage(pageIndex);
      setPageLen(data.data.dataLen);
      let t_village = JSON.parse(JSON.stringify(villageArr));
      for (let i = 0; i < myquesArr.length; i++) {
        let villageCode = myquesArr[i].body[0].contents[1].answer.trim();
        if (villageCode != "" && myquesArr[i].state != 0) {
          // console.log(
          //   "村代码---",
          //   villageCode,
          //   "---",
          //   t_village.indexOf(villageCode)
          // );
          if (t_village.indexOf(villageCode) == -1) {
            t_village.push(villageCode);
          }
        }
      }
      setVillageArr(JSON.parse(JSON.stringify(t_village)));
      // console.log("村代码数组---", villageArr);
      setMyQuesLoading("end");
    } catch (error) {
      console.log("找不到我的问卷---", error);
      setMyQuesLoading("error");
    }
  };

  const operateNum = (num1, flag, num2) => {
    let result = 0;
    if (flag == 1) {
      result = num1 + num2;
    } else if (flag == 2) {
      result = num1 - num2;
    } else if (flag == 3) {
      if (num2 == 0) {
        result = "err";
      } else {
        result = Math.round(num1 / num2);
      }
    }
    return result;
  };

  const getNumAnswer = (quesIndex, arr) => {
    let result = 0;
    let title;
    if (arr.length == 2) {
      console.log("题号---", arr[0], "-", arr[1]);
      title = MyQuesData[quesIndex].body[arr[0]].contents[arr[1]];
    } else if (arr.length == 3) {
      console.log("题号---", arr[0], "-", arr[1], "-", arr[2]);
      title = MyQuesData[quesIndex].body[arr[0]].contents[arr[1]].title[arr[2]];
    }
    if (title.type == 7) {
      result = Number(title.answer);
    } else if (title.type == 2 && title.answer != -1) {
      if (title.optionFlag[title.answer][0]) {
        result = Number(title.optionFlag[title.answer][1]);
      } else {
        result = 0;
      }
    }
    return result;
  };

  // 上传问卷
  const postMyQues = async (quesIndex, callback) => {
    let errorStr = "";
    if (MyQuesData[quesIndex].title == "") {
      errorStr = errorStr + "问卷编号,";
    }
    for (let i = 0; i < MyQuesData[quesIndex].body.length; i++) {
      if (MyQuesData[quesIndex].body[i].visible) {
        for (
          let j = 0;
          j < MyQuesData[quesIndex].body[i].contents.length;
          j++
        ) {
          let t_contents = MyQuesData[quesIndex].body[i].contents[j];
          if (t_contents.visible) {
            if (
              (t_contents.type == 1 || t_contents.type == 7) &&
              t_contents.answer == ""
            ) {
              errorStr =
                errorStr + String.fromCharCode(i + 65) + (j + 1) + "，";
            } else if (
              t_contents.type == 2 &&
              (t_contents.answer < 0 ||
                t_contents.answer >= t_contents.options.length)
            ) {
              errorStr =
                errorStr + String.fromCharCode(i + 65) + (j + 1) + "，";
            } else if (t_contents.type == 3) {
              let flag = t_contents.answer[0];
              for (let n = 1; n < t_contents.answer.length; n++) {
                flag = flag || t_contents.answer[n];
              }
              if (!flag)
                errorStr =
                  errorStr + String.fromCharCode(i + 65) + (j + 1) + "，";
            } else if (t_contents.type == 5) {
              for (let k = 0; k < t_contents.title.length; k++) {
                let t_title = t_contents.title[k];
                if (t_title.visible) {
                  if (
                    (t_title.type == 1 || t_title.type == 7) &&
                    t_title.answer == ""
                  ) {
                    errorStr =
                      errorStr +
                      String.fromCharCode(i + 65) +
                      (j + 1) +
                      String.fromCharCode(k + 97) +
                      "，";
                  } else if (
                    t_title.type == 2 &&
                    (t_title.answer < 0 ||
                      t_title.answer >= t_title.options.length)
                  ) {
                    errorStr =
                      errorStr +
                      String.fromCharCode(i + 65) +
                      (j + 1) +
                      String.fromCharCode(k + 97) +
                      "，";
                  } else if (t_title.type == 3) {
                    let flag = t_title.answer[0];
                    for (let n = 1; n < t_title.answer.length; n++) {
                      flag = flag || t_title.answer[n];
                    }
                    if (!flag)
                      errorStr =
                        errorStr +
                        String.fromCharCode(i + 65) +
                        (j + 1) +
                        String.fromCharCode(k + 97) +
                        "，";
                  } else if (t_title.type == 6) {
                    if (
                      t_title.answer[0] == "" ||
                      t_title.answer < 1 ||
                      t_title.answer[0] == null
                    ) {
                      errorStr = errorStr + "A1a，";
                    }
                    if (
                      t_title.answer[1] == "" ||
                      t_title.answer < 2 ||
                      t_title.answer[1] == null
                    ) {
                      errorStr = errorStr + "A1b，";
                    }
                    if (
                      t_title.answer[2] == "" ||
                      t_title.answer < 3 ||
                      t_title.answer[2] == null
                    ) {
                      errorStr = errorStr + "A1c，";
                    }
                    if (
                      t_title.answer[3] == "" ||
                      t_title.answer < 4 ||
                      t_title.answer[3] == null
                    ) {
                      errorStr = errorStr + "A1d，";
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    setErrorAlter(errorStr);
    console.log("没填的---", errorAlter);
    if (errorStr == "") {
      let c2Flag = false;
      let conditionStr = "";
      for (let a = 0; a < condition.length; a++) {
        let goonFlag = true;
        if (condition[a].num.length == 2) {
          goonFlag =
            MyQuesData[quesIndex].body[condition[a].num[0]].contents[
              condition[a].num[1]
            ].visible &&
            MyQuesData[quesIndex].body[condition[a].num[0]].visible;
        } else {
          goonFlag =
            MyQuesData[quesIndex].body[condition[a].num[0]].contents[
              condition[a].num[1]
            ].title[condition[a].num[2]].visible &&
            MyQuesData[quesIndex].body[condition[a].num[0]].contents[
              condition[a].num[1]
            ].visible &&
            MyQuesData[quesIndex].body[condition[a].num[0]].visible;
        }
        if (goonFlag) {
          let left = 0;
          let right = 0;
          let t_num = [];
          left = getNumAnswer(quesIndex, condition[a].num);

          for (let b = 0; b < condition[a].conType.length; b++) {
            right = 0;
            if (condition[a].conType[b] == 0) {
              // 是否等于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                // console.log("---", right);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
                // console.log("++", right);
              }
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left != right) {
                console.log(
                  "右---",
                  right,
                  "---有错---",
                  condition[a].conStr[b]
                );
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 1) {
              // 大于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              // console.log(">1 右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left <= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 2) {
              // 大于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log(">2 右---", right);
              if (left <= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 3) {
              // 小于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              // console.log("<1 右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left >= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 4) {
              // 小于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log("<2 右---", right);
              if (left >= right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 5) {
              // 大于等于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              // console.log(">=1 右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left < right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 6) {
              // 大于等于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log(">=2 右---", right);
              if (left < right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 7) {
              // 小于等于表达式
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                let num2;
                t_num = JSON.parse(JSON.stringify(condition[a].conArr[b][c]));
                t_num.splice(0, 1);
                num2 = getNumAnswer(quesIndex, t_num);
                right = operateNum(right, condition[a].conArr[b][c][0], num2);
              }
              console.log("<=1 ", "左--", left, "右---", right);
              if (right == "err" && !c2Flag) {
                conditionStr = conditionStr + "C2不为0；\n";
                c2Flag = true;
              } else if (left > right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            } else if (condition[a].conType[b] == 8) {
              // 小于等于数字
              for (let c = 0; c < condition[a].conArr[b].length; c++) {
                right = condition[a].conArr[b][0];
              }
              // console.log("<=2 右---", right);
              if (left > right) {
                // console.log("右---", right, "---有错---", condition[a].conStr[b]);
                conditionStr = conditionStr + condition[a].conStr[b] + "，\n";
              }
            }
          }
        }
      }
      setConditionAlter(conditionStr);
      console.log("填错的---", conditionAlter);
      if (conditionStr == "") {
        Alert.alert("提示", "确认上传这份问卷吗?", [
          {
            text: "取消",
            onPress: () => console.log("Cancel Pressed"),
            style: "cancel",
          },
          {
            text: "确定",

            onPress: async () => {
              try {
                let ques_data = {
                  ...MyQuesData[quesIndex],
                  opinions: MyQuesData[quesIndex].opinions._id,
                  userproblem: MyQuesData[quesIndex].userproblem._id,
                  filedata: MyQuesData[quesIndex].filedata._id,
                  state: 1,
                  user: MyQuesData[quesIndex].user._id,
                  group: MyQuesData[quesIndex].user.group,
                  time: new Date(),
                  target: MyQuesData[quesIndex].body[0].contents[5].answer,
                };
                // console.log("上传---", ques_data.filedata);
                let ques_req_data = await queryApi.patch("userques/", {
                  Ques: ques_data,
                  flag: "upload",
                });
                console.log("上传用户问卷成功---", ques_req_data.data.status);
                dispatch({
                  type: "edit_state",
                  payload: { index: quesIndex, t_state: 1 },
                });
                let t_village = JSON.parse(JSON.stringify(villageArr));
                let villageCode =
                  MyQuesData[quesIndex].body[0].contents[1].answer.trim();
                if (villageCode != "") {
                  if (t_village.indexOf(villageCode) == -1) {
                    t_village.push(villageCode);
                  }
                }
                setVillageArr(JSON.parse(JSON.stringify(t_village)));
                // console.log("村代码数组---", villageArr);
                Alert.alert("上传问卷成功");
                callback(true);
              } catch (error) {
                callback(false);
                console.log("上传问卷失败---", error);
                Alert.alert("上传问卷失败");
              }
            },
          },
        ]);
      }
    }
  };

  // 删除问卷
  const deleteMyQues = async (quesIndex) => {
    console.log("-------", quesIndex);
    if (quesIndex < 0 || quesIndex >= MyQuesData.length) {
      Alert.alert("请先选择要删除的问卷");
    } else if (MyQuesData[quesIndex].state == 3) {
      Alert.alert("已上传过问卷不支持删除");
    } else {
      try {
        console.log("删除的序号---", quesIndex);
        let req_data = {
          ques_id: MyQuesData[quesIndex]._id,
          filedata_id: MyQuesData[quesIndex].filedata._id,
          problem_id: MyQuesData[quesIndex].userproblem._id,
          opinion_id: MyQuesData[quesIndex].opinions._id,
        };
        let res_data = await queryApi.delete("userques/", { params: req_data });
        console.log("删除问卷成功---", res_data.data.status);
        dispatch({
          type: "delete_myques",
          payload: { quesIndex },
        });
        Alert.alert("删除成功");
      } catch (error) {
        console.log("删除问卷失败---", error);
        Alert.alert("删除失败");
      }
    }
  };

  // 添加问卷
  const postMyOneQues = async (userques, state, callback) => {
    const user = store.getState().authR.user;
    // console.log(userques);
    let newQuesData;
    try {
      let proData = {
        ...userques.userproblem,
        user: user._id,
        time: new Date(),
      };
      let pro_req_data = await queryApi.post("userproblem/", proData);
      console.log("添加用户问题清单成功---", pro_req_data.data.status);
      let pro_id = pro_req_data.data.data._id;

      let opinion_data = {
        opinions: [],
      };
      let opinions_req_data = await queryApi.post("opinion/", opinion_data);
      console.log("添加用户意见数组成功---", opinions_req_data.data.status);
      let opinion_id = opinions_req_data.data.data._id;

      let file_data = {
        image: [],
        video: [],
        soundfile: [],
      };
      let file_req_data = await queryApi.post("filedata", file_data);
      console.log("添加入户资料成功---", file_req_data.data.status);
      let file_id = file_req_data.data.data._id;

      let ques_data = {
        ...userques,
        state: state,
        user: user._id,
        group: user.group,
        userproblem: pro_id,
        opinions: opinion_id,
        filedata: file_id,
        time: new Date(),
        target: userques.body[0].contents[5].answer,
      };
      console.log("开始往后端传啦---");
      let ques_req_data = await queryApi.post("userques/", ques_data);
      console.log("添加用户问卷成功---", ques_req_data.data.status);
      // console.log("ques_id---", ques_req_data.data.data._id);
      console.log("传完啦");
      let newQuesData = await queryApi.get(
        "userques/" + ques_req_data.data.data._id
      );
      // console.log(
      //   "查完啦",
      //   newQuesData.data.data.title,
      //   newQuesData.data.data.user,
      //   newQuesData.data.data.userproblem,
      //   newQuesData.data.data.opinions
      // );
      dispatch({
        type: "add_data",
        payload: { newQues: newQuesData.data.data },
      });
      console.log("插入啦");
      callback(true);
      Alert.alert("保存成功");
    } catch (error) {
      callback(false);
      Alert.alert("保存失败");
      console.log("添加失败---", error);
    }
    return newQuesData;
  };

  // 添加评论
  const addReply = async (quesIndex, replyDetail) => {
    const user = store.getState().authR.user;
    let replyArr = {
      ...MyQuesData[quesIndex].opinions,
      opinions: [
        ...MyQuesData[quesIndex].opinions.opinions,
        {
          ...replyDetail,
          publisher: user.name,
        },
      ],
    };
    // console.log("replyArr---", replyArr);
    try {
      await queryApi.patch("opinion/" + replyArr._id, replyArr);
      let AllData = await queryApi.get("opinion/" + replyArr._id);
      dispatch({
        type: "edit_opinions",
        payload: { quesIndex: quesIndex, opinions: AllData.data.data },
      });
    } catch (error) {
      console.log("添加评论失败---", error);
    }
  };

  // 修改入户资料
  const editFileData = async (
    quesIndex,
    editData,
    originImages,
    deleteOriginImages,
    originAudio,
    deleteOriginAudio,
    originVideos,
    deleteOriginVideos,
    callback
  ) => {
    setFileDataLoading("ing");
    // console.log("入户资料---", editData);
    try {
      if (
        editData.image.length != 0 ||
        editData.video.length != 0 ||
        editData.soundfile.length != 0 ||
        deleteOriginImages.length != 0 ||
        deleteOriginVideos.length != 0 ||
        deleteOriginAudio.length != 0 ||
        originImages.length != 0 ||
        originAudio.length != 0
      ) {
        let formData = new FormData();
        if (editData.image.length != 0) {
          editData.image.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "image/" + item.split(".").pop(),
            });
          });
        }
        if (editData.video.length != 0) {
          editData.video.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "video/" + item.split(".").pop(),
            });
          });
        }
        if (editData.soundfile.length != 0) {
          editData.soundfile.forEach((item) => {
            formData.append("files", {
              name: item.uri.split("/").pop(),
              uri: item.uri,
              type: "audio/" + item.uri.split(".").pop(),
            });
          });
        }
        //需删除的原始图片、视频
        if (deleteOriginImages.length != 0) {
          deleteOriginImages.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        if (deleteOriginVideos.length != 0) {
          deleteOriginVideos.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        if (deleteOriginAudio.length != 0) {
          deleteOriginAudio.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        //需保留的原始图片、视频
        if (originImages.length != 0) {
          originImages.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        if (originVideos.length != 0) {
          originVideos.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        if (originAudio.length != 0) {
          originAudio.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        console.log("----------request-------------", formData);
        let res = await fetch(fileWeb + "/upload/multi", {
          method: "patch",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          body: formData,
        });
        let response = await res.json();
        editData.image = response.message.filter(
          (item) => item.fileType.split("/").shift() == "image"
        );
        editData.video = response.message.filter(
          (item) => item.fileType.split("/").shift() == "video"
        );
        editData.soundfile = response.message.filter(
          (item) => item.fileType.split("/").shift() == "audio"
        );
      }
      //对后端进行修改
      const result = await queryApi.patch(
        "/filedata/" + editData._id,
        editData
      );
      console.log("入户资料修改成功---", result.data.data);
      let AllData = await queryApi.get("filedata/" + editData._id);
      console.log("添加评论成功---", AllData.data.data);
      dispatch({
        type: "edit_filedata",
        payload: { quesIndex: quesIndex, filedata: AllData.data.data },
      });
      setFileDataLoading("end");
      callback(true);
      Alert.alert("更新入户资料成功");
    } catch (error) {
      setFileDataLoading("error");
      callback(false);
      Alert.alert("更新入户资料失败");
      console.log("入户资料修改失败---", error);
    }
  };

  const generateExcel = (ExcelData, ExcelTitle) => {
    let wb = XLSX.utils.book_new();
    let ws;
    for (let i = 0; i < ExcelData.length; i++) {
      if (ExcelData[i].length > 2) {
        // console.log(ExcelData[i]);
        ws = XLSX.utils.aoa_to_sheet(ExcelData[i]);
        XLSX.utils.book_append_sheet(wb, ws, typeOptions[i], true);
      }
    }
    // 工作簿

    // 工作表

    // let ws = XLSX.utils.aoa_to_sheet([
    //   ["Odd", "Even", "Total"],
    //   [1, 2, { t: "n", v: 3, f: "A2+B2" }], // t:"n" 类型：number
    //   [3, 4, { t: "n", v: 3, f: "A3+B3" }],
    //   [5, 6, { t: "n", v: 3, f: "A4+B4" }],
    // ]);

    // append the sheet to the worbook
    // sheetname：MyFirstSheet
    // XLSX.utils.book_append_sheet(wb, ws, "问卷", true);

    // rrefer to it by name and the use the ! mark and then specify the cell that i'm interested
    // let ws2 = XLSX.utils.aoa_to_sheet([
    //   ["Odd*2", "Even*2", "Total"],
    //   [
    //     { t: "n", f: "MyFirstSheet!A2*2" },
    //     { t: "n", f: "MyFirstSheet!B2*2" },
    //     { t: "n", f: "A2+B2" },
    //   ],
    //   [
    //     { t: "n", f: "MyFirstSheet!A3*2" },
    //     { t: "n", f: "MyFirstSheet!B3*2" },
    //     { t: "n", f: "A3+B4" },
    //   ],
    //   [
    //     { t: "n", f: "MyFirstSheet!A4*2" },
    //     { t: "n", f: "MyFirstSheet!B4*2" },
    //     { t: "n", f: "A4+B4" },
    //   ],
    // ]);

    // generate the base64 content of my workbook
    const base64 = XLSX.write(wb, { type: "base64" });
    const filename = FileSystem.documentDirectory + "问卷.xlsx";
    FileSystem.writeAsStringAsync(filename, base64, {
      encoding: FileSystem.EncodingType.Base64,
    }).then(() => {
      Sharing.shareAsync(filename);
    });
  };

  // 导出Excel
  const exportExcel = async (quesArr, ExcelTitle) => {
    try {
      let idArr = [];
      for (let i = 0; i < quesArr.length; i++) {
        if (quesArr[i]) {
          idArr.push(MyQuesData[i]._id);
        }
      }
      let data = await queryApi.get("userques/exceldata", {
        params: { idArr: idArr },
      });
      console.log("获取Excel表数据成功---", data.data.status);
      generateExcel(data.data.data);
    } catch (error) {
      Alert.alert("导出问卷失败");
      console.log("导出Excel表失败---", error);
    }
  };

  return (
    <MyQuesContext.Provider
      value={{
        myQuesLoading,
        fileDataLoading,
        userProLoading,
        MyQuesData,
        villageArr,
        errorAlter,
        conditionAlter,
        pageLen,
        addNewQues,
        editMyQues,
        editAndJudgeMyQues,
        editQuesProblem,
        postMyQues,
        getMyQues,
        addReply,
        editFileData,
        exportExcel,
        deleteMyQues,
      }}
    >
      {children}
    </MyQuesContext.Provider>
  );
};

export default MyQuesContext;

// body: [
//   {
//     type: 0, // 0：题目组
//     head: "农户基本信息",
//     visible: true,
//     contents: [
//       {
//         type: 1, // 1：问答题
//         needAnswer: true,
//         title: "村代码",
//         visible: true,
//         answer: "001",
//         skipType: 0,
//         relation: [],
//         skipDetail: [
//           {
//             condition: [],
//             skipNumber: [],
//           },
//         ],
//       },
//       {
//         type: 2, // 2：单选题
//         visible: true,
//         needAnswer: true,
//         title: "调查点类型",
//         options: ["脱贫村", "其他村"],
//         answer: 1,
//         optionFlag: [
//           [false, ""],
//           [false, ""],
//         ],
//         skipType: 1,
//         relation: [],
//         skipDetail: [
//           {
//             condition: [0],
//             skipNumber: [[1, 1]],
//           },
//         ],
//       },
//       {
//         type: 2, // 2：单选题
//         visible: true,
//         needAnswer: true,
//         title: "义务教育阶段，孩子是否都上学了",
//         options: ["是", "否，有____人没上学"],
//         optionFlag: [
//           [false, ""],
//           [true, ""],
//         ],
//         answer: 1,
//         skipType: 0,
//         relation: [],
//         skipDetail: [
//           {
//             condition: [],
//             skipNumber: [],
//           },
//         ],
//       },
//     ],
//   },
//   {
//     type: 0, // 0：题目组
//     visible: true,
//     head: "一些题目",
//     contents: [
//       {
//         type: 1, // 1：问答题
//         visible: true,
//         needAnswer: true,
//         title: "被访者姓名",
//         answer: "某某某",
//         skipType: 0,
//         relation: [],
//         skipDetail: [
//           {
//             condition: [],
//             skipNumber: [],
//           },
//         ],
//       },
//       {
//         type: 2, // 2：单选题
//         visible: true,
//         title: "与户主关系",
//         needAnswer: true,
//         options: ["本人", "配偶", "子女", "父母", "其他"],
//         optionFlag: [
//           [false, ""],
//           [false, ""],
//           [false, ""],
//           [false, ""],
//           [false, ""],
//         ],
//         answer: 0,
//         skipType: 0,
//         relation: [],
//         skipDetail: [
//           {
//             condition: [],
//             skipNumber: [],
//           },
//         ],
//       },
//       {
//         title: "联系电话",
//         visible: true,
//         needAnswer: true,
//         type: 1, // 1：问答题
//         answer: "10086",
//         skipType: 0,
//         relation: [],
//         skipDetail: [
//           {
//             condition: [],
//             skipNumber: [],
//           },
//         ],
//       },
//     ],
//   },
// ],
